package com.analysis.controller;

import com.analysis.dto.ApiResponse;
import com.analysis.entity.BrandExposureSnapshot;
import com.analysis.entity.Project;
import com.analysis.enums.RequireLogin;
import com.analysis.service.BrandExposureSnapshotService;
import com.analysis.service.ProjectService;
import com.analysis.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 品牌曝光快照
 */
@RestController
@RequestMapping("/api/brand/snapshots")
@CrossOrigin(origins = "*")
public class BrandExposureSnapshotController {

    @Autowired
    private BrandExposureSnapshotService snapshotService;

    @Autowired
    private ProjectService projectService;

    @PostMapping("/add")
    @RequireLogin
    public ApiResponse<BrandExposureSnapshot> create(@RequestBody BrandExposureSnapshot snapshot, HttpServletRequest request) {
        if (StringUtils.isBlank(snapshot.getProductName())) {
            return ApiResponse.error("品牌名称不能为空");
        }
        if (StringUtils.isBlank(snapshot.getQuestion())) {
            return ApiResponse.error("问题列表不能为空");
        }
        try {
            // 设置项目ID
            initProjectId(snapshot, request);

            int result = snapshotService.create(snapshot);

            return result > 0 ? ApiResponse.success(snapshot) : ApiResponse.error("创建失败");
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("创建快照时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/delete")
    @RequireLogin
    public ApiResponse<String> delete(HttpServletRequest request, Long id) {
        try {
            Long projectId = getProjectId(request);

            // 检查项目是否存在且属于当前用户
            BrandExposureSnapshot existing = snapshotService.getById(id);
            if (existing == null || !existing.getProjectId().equals(projectId)) {
                return ApiResponse.error("无权限操作");
            }
            int result = snapshotService.delete(id);
            return result > 0 ? ApiResponse.success("删除成功") : ApiResponse.error("删除失败或不存在");
        } catch (Exception e) {
            return ApiResponse.error("删除快照时发生错误: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    @RequireLogin
    public ApiResponse<BrandExposureSnapshot> update(@RequestBody BrandExposureSnapshot snapshot, HttpServletRequest request) {
        try {
            initProjectId(snapshot, request);

            // 检查项目是否存在且属于当前用户
            BrandExposureSnapshot existing = snapshotService.getById(snapshot.getId());
            if (existing == null || !existing.getProjectId().equals(snapshot.getProjectId())) {
                return ApiResponse.error("无权限操作");
            }
            int result = snapshotService.update(snapshot);
            return result > 0 ? ApiResponse.success(existing) : ApiResponse.error("更新失败或不存在");
        } catch (Exception e) {
            return ApiResponse.error("更新快照时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/get")
    @RequireLogin
    public ApiResponse<BrandExposureSnapshot> getById(Long id) {
        try {
            BrandExposureSnapshot data = snapshotService.getWithContentById(id);
            return data != null ? ApiResponse.success(data) : ApiResponse.error("不存在");
        } catch (Exception e) {
            return ApiResponse.error("查询快照详情时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/page")
    @RequireLogin
    public ApiResponse<Map<String, Object>> page(@RequestParam int pageNum, @RequestParam int pageSize, HttpServletRequest request) {
        try {
            Long projectId = getProjectId(request);

            List<BrandExposureSnapshot> list = snapshotService.page(projectId, pageNum, pageSize);
            int total = snapshotService.count(projectId);
            Map<String, Object> data = new HashMap<>();
            data.put("list", list);
            data.put("total", total);
            data.put("pageNum", pageNum);
            data.put("pageSize", pageSize);
            return ApiResponse.success(data);
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("分页查询快照时发生错误: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @RequireLogin
    public ApiResponse<List<BrandExposureSnapshot>> list(HttpServletRequest request) {
        try {
            Long projectId = getProjectId(request);

            List<BrandExposureSnapshot> list = snapshotService.listByProject(projectId);
            return ApiResponse.success(list);
        } catch (IllegalStateException e) {
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            return ApiResponse.error("查询快照列表时发生错误: " + e.getMessage());
        }
    }

    public Long getProjectId(HttpServletRequest request) {
        Long companyId = UserUtils.getCurrentUserOrThrow(request).getCompanyId();
        Project project = projectService.getSelectedByCompanyId(companyId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在或无权限操作");
        }
        return project.getId();
    }


    public void initProjectId(BrandExposureSnapshot snapshot, HttpServletRequest request) {
        Long companyId = UserUtils.getCurrentUserOrThrow(request).getCompanyId();
        Project project = projectService.getSelectedByCompanyId(companyId);
        if (project == null) {
            throw new IllegalArgumentException("项目不存在或无权限操作");
        }
        snapshot.setProjectId(project.getId());
        snapshot.setCompanyId(companyId);
    }


}


